package com.audaque.springboot.foshanupload.web.admin.listener;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import de.codecentric.boot.admin.server.domain.values.InstanceId;
import de.codecentric.boot.admin.server.domain.values.Registration;
import de.codecentric.boot.admin.server.utils.jackson.AdminServerModule;
import de.codecentric.boot.admin.server.utils.jackson.InstanceIdMixin;
import de.codecentric.boot.admin.server.utils.jackson.RegistrationDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author zgb
 * @desc ...
 * @date 2023-07-09 19:43:39
 */
@Component
@Slf4j
public class AdminBeanPostProcessorListener implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        log.debug("postProcessBeforeInitialization 在初始化方法前执行");
        log(bean, beanName);
        //配合instance  of 做bean加工

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        log.debug("postProcessAfterInitialization 在初始化方法后执行");
        log(bean, beanName);
        //配合instance  of 做bean加工
        if (bean instanceof ObjectMapper) {
            ObjectMapper objectMapper = (ObjectMapper) bean;
            //加工

            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

            objectMapper.addMixIn(InstanceId.class, InstanceIdMixin.class);
            String[] pwdConstructor = new String[]{".*password$"};
            objectMapper.registerModule(new AdminServerModule(pwdConstructor));

            SimpleModule simpleModule = new SimpleModule();
            simpleModule.addSerializer(Registration.class, ToStringSerializer.instance);
            simpleModule.addDeserializer(Registration.class, new RegistrationDeserializer());
            String moduleName = simpleModule.getModuleName();
            log.debug("moduleName:"+moduleName);
            objectMapper.registerModule(simpleModule);
        }
        return bean;
    }


    private void log(Object bean, String beanName) {
        log.debug("bean:" + bean);
        log.debug("beanName:" + beanName);
        Class<?> aClass = bean.getClass();
        String className = aClass.getName();
        log.debug("className:" + className);
    }


}
